#include <stdio.h>
#include <stdlib.h>


typedef int ElmtType;

struct List{
    /* data */
    ElmtType* array;
    int capacity;
    int size;
};

typedef struct List* ArrayList;

int initList(ArrayList list){
    list->capacity = 10;
    list->array = malloc(sizeof(ElmtType) * list->capacity);
    if(list->array == NULL) return 0;
    list->size = 0;

    return 1;
}

int insertList(ArrayList list, ElmtType e, int index){
    if(index < 1 || index > list->size + 1) return 0; //判断插入位置是否允许，不允许就不运行后续

    if(list->size == list->capacity){
        int newCapacity = list->capacity + (list->capacity >> 1);
        ElmtType* newArray = realloc(list->array, newCapacity * sizeof(ElmtType));
        
        if(newArray == NULL) return 0;
        list->array = newArray;
        list->capacity = newCapacity;
    
    }



    for(int i = list->size; i > index - 1; i--)
        list->array[i] = list->array[i - 1];
    list->array[index - 1] = e;
    list->size++;

    return 1;
}

int delList(ArrayList list, int index)
{
    if(index < 1 || index > list->size) return 0;
    for(int i = index - 1; i < list->size; ++i){
        list->array[i] = list->array[i + 1];
    }
    list->size--;
    return 1;
}

int sizeList(ArrayList list){
    return list->size;
}

ElmtType* getList(ArrayList list, int index){
    if(index < 1 || index > list->size) return NULL;
    return &list->array[index - 1];
}
int findList(ArrayList list, ElmtType e){
    for(int i = 0; i < list->size; i++){
        if(list->array[i] == e) return i + 1;
    }

    return -1;
}

void printList(ArrayList list){   //编写一个函数用于打印表当前的数据
    for (int i = 0; i < list->size; ++i)   //表里面每个元素都拿出来打印一次
        printf("%d ", list->array[i]);
    printf("\n");
}

int main(void){
    struct List list;
    if(initList(&list)){
        for(int i = 0; i < 30; i++){
            insertList(&list, i , i + 1);
        }
        delList(&list, 10);
        printList(&list);
        printf("%d\n",list.capacity);
        printf("%d\n", *getList(&list, 3));
        printf("Found, it's at %d\n",findList(&list, 5));
    }
    else{
        printf("Init Error");
    }
}
